//
//  MainTabBarController.swift
//  Swift_Weibo
//
//  Created by Tim on 2019/8/13.
//  Copyright © 2019 Tim. All rights reserved.
//  全局根视图管理器

import UIKit

class MainTabBarController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildren()
        setupComposeBtn()
    }
    
    @objc private func composeAction() {
        // FIXME: - 撰写按钮逻辑未实现
        debugLog("开始撰写微博")
    }
    
    /// 撰写按钮懒加载
    private lazy var composeBtn = UIButton.imageBtn(imgName: "tabbar_compose_icon_add", backgroundImgName: "tabbar_compose_button")
}

extension MainTabBarController {
    
    /// 配置撰写微博按钮
    private func setupComposeBtn() {
        tabBar.addSubview(composeBtn)
        let count = children.count
        let width = tabBar.bounds.width / CGFloat(count) - 1
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0)
        composeBtn.addTarget(self, action: #selector(composeAction), for: .touchUpInside)
    }
    
    /// 配置所有子视图
    private func setupChildren() {
        // 配置文件路径，默认存储到 document/main.json
        let jsonPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("main.json")
        debugLog(jsonPath)
        // 读取 data 数据
        var jsonData = NSData(contentsOfFile: jsonPath)
        
        if jsonData == nil {
            let bundlePath = Bundle.main.path(forResource: "main.json", ofType: nil)
            jsonData = NSData(contentsOfFile: bundlePath!)
        }
        
        // 转换 Data 数据为 json 数据
        guard let json = try? JSONSerialization.jsonObject(with: jsonData! as Data, options: []) as? [[String : Any]] else {
            return
        }
        
        
        /// 子视图控制器数组
        var children = [UIViewController]()
        
        for dict in json {
            children.append(setupChild(dict: dict))
        }
        
        viewControllers = children
    }
    
    private func setupChild(dict: [String : Any]) -> UIViewController {
        guard let clsName = dict["className"] as? String,
            let title = dict["title"] as? String,
            let imgName = dict["imgName"] as? String,
            let visitorInfo = dict["visitorInfo"] as? [String : String],
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type else {
                return UIViewController()
        }
        
        // 创建当前控制器
        let currentVC = cls.init()
        currentVC.title = title
        currentVC.tabBarItem.image = UIImage(named: "tabbar_" + imgName)
        currentVC.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imgName + "_selected")?.withRenderingMode(.alwaysOriginal)
        currentVC.visitorInfo = visitorInfo
        currentVC.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.orange], for: .selected)
        
        let nav = MainNavigationController(rootViewController: currentVC)
        
        return nav
    }
}
